export const formatTime = (date: Date) => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return (
    [year, month, day].map(formatNumber).join('/') +
    ' ' +
    [hour, minute, second].map(formatNumber).join(':')
  )
}

const formatNumber = (n: number) => {
  const s = n.toString()
  return s[1] ? s : '0' + s
}

/**
 * 智能时间格式化函数
  * 规则：
  * 1. 今天的消息只显示时间，如 "15:30"
  * 2. 昨天的消息显示 "昨天 15:30"
  * 3. 一周内的消息显示 "周几 15:30"
  * 4. 今年内的消息显示 "MM-dd HH:mm"
  * 5. 往年的消息显示 "yyyy-MM-dd HH:mm"
 * @param timestamp 时间戳（毫秒）或时间字符串
 * @param type 显示类型：'chat' 聊天详情页 | 'list' 消息列表页
 * @returns 格式化后的时间字符串
 */
export const formatSmartTime = (timestamp: number | string, type: 'chat' | 'list' = 'chat'): string => {
  if (!timestamp) return '';
  
  const date = typeof timestamp === 'string' ? new Date(timestamp) : new Date(timestamp);
  const now = new Date();
  
  // 格式化时间部分
  const timeStr = `${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
  
  // 判断是否是今天
  const isToday = date.getDate() === now.getDate() && 
                  date.getMonth() === now.getMonth() && 
                  date.getFullYear() === now.getFullYear();
  
  if (isToday) {
    // 今天的消息只显示时间
    return timeStr;
  }
  
  // 判断是否是昨天
  const yesterday = new Date(now);
  yesterday.setDate(yesterday.getDate() - 1);
  const isYesterday = date.getDate() === yesterday.getDate() && 
                      date.getMonth() === yesterday.getMonth() && 
                      date.getFullYear() === yesterday.getFullYear();
  
  if (isYesterday) {
    // 昨天的消息
    return type === 'chat' ? `昨天 ${timeStr}` : '昨天';
  }
  
  // 判断是否是一周内（7天内）
  const sevenDaysAgo = new Date(now);
  sevenDaysAgo.setDate(now.getDate() - 7);
  sevenDaysAgo.setHours(0, 0, 0, 0);
  
  const isWithinWeek = date >= sevenDaysAgo && date < now;
  
  if (isWithinWeek) {
    // 一周内的消息显示星期
    const weekdays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
    return type === 'chat' ? `${weekdays[date.getDay()]} ${timeStr}` : weekdays[date.getDay()];
  }
  
  // 判断是否是今年
  const isThisYear = date.getFullYear() === now.getFullYear();
  
  if (isThisYear) {
    // 今年内的消息
    const month = (date.getMonth() + 1).toString().padStart(2, '0');
    const day = date.getDate().toString().padStart(2, '0');
    return type === 'chat' ? `${month}-${day} ${timeStr}` : `${month}/${day}`;
  } else {
    // 往年的消息
    const year = date.getFullYear();
    const month = (date.getMonth() + 1).toString().padStart(2, '0');
    const day = date.getDate().toString().padStart(2, '0');
    return type === 'chat' ? `${year}-${month}-${day} ${timeStr}` : `${year}/${month}/${day}`;
  }
}
